from django.shortcuts import render_to_response, redirect
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.http import HttpResponse, HttpResponseBadRequest

from client.models import Brands, Regions
from client.forms import RegistrationForm

def index(request):
    allBrands = Brands.objects.all()
    return render_to_response('client/index.html', {"brands": allBrands})

def registration(request):
    c = {}
    c.update(csrf(request))
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/profile')
    else:
        form = RegistrationForm(initial={"regions": "1"})

    c.update({'form': form})
    return render_to_response('client/registration.html', c)

@csrf_exempt
def region_city(request):
    if request.is_ajax():
        region_id = int(request.POST.get("region_id"))
        region = Regions.objects.get(id="%d" % region_id)
        data = serializers.serialize("json", region.city.all())
        return HttpResponse(data, "json")

    return HttpResponseBadRequest()

def bucket(request):
    return render_to_response('client/bucket.html')

def settings(request):
    return render_to_response('client/settings.html')

def orders(request):
    return render_to_response('client/orders.html')

def authorization(request):
    pass

def profile(request):
    return render_to_response('client/profile.html')

def finance(request):
    return render_to_response('client/finance.html')

def garage(request):
    return render_to_response('client/garage.html')

def loyalty_program(request):
    return render_to_response('client/loyalty_program.html')

def car_brand(request, brand):
    return render_to_response('client/car_brand.html', {"brand": brand})
